import os
import pandas as pd
import numpy as np
import json
from sklearn.metrics.pairwise import cosine_similarity
import requests
import time
from dotenv import load_dotenv

# 环境变量加载
load_dotenv()

# 读取用户评价数据集
df = pd.read_csv("D:/ideaSpace/rag-in-action-master/90-文档-Data/灭神纪/用户评价.csv")

# 读取游戏描述文件
with open("D:/ideaSpace/rag-in-action-master/90-文档-Data/灭神纪/游戏说明.json", "r") as f:
    game_descriptions = json.load(f)

# 智谱AI API配置
ZHIPU_API_KEY = os.getenv("ZHIPUAI_API_KEY")  # 替换为你的智谱API密钥
print(ZHIPU_API_KEY)
EMBEDDING_API_URL = "https://open.bigmodel.cn/api/paas/v4/embeddings"  # 假设的API端点，请根据实际文档调整

# 定义函数获取智谱AI的嵌入向量
def get_zhipu_embedding(text, model="text_embedding"):
    headers = {
        "Authorization": f"Bearer {ZHIPU_API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,
        "input": [text]
    }

    retries = 3
    for i in range(retries):
        try:
            response = requests.post(EMBEDDING_API_URL, headers=headers, json=data)
            response.raise_for_status()
            embedding = response.json()['data'][0]['embedding']
            return np.array(embedding)
        except Exception as e:
            if i == retries - 1:
                raise
            time.sleep(2 ** i)  # 指数退避

# 获取所有游戏的嵌入向量
unique_games = df['game_title'].unique().tolist()
target_game = "Killing God: Hu Sun"  # 目标游戏名称更改
if target_game not in unique_games:
    unique_games.append(target_game)  # 确保目标游戏在列表中
game_embeddings = {}
for game in unique_games:
    description = game_descriptions[game]
    game_embeddings[game] = np.array(get_zhipu_embedding(description))

# 计算用户评价的嵌入向量（该用户评价过的所有游戏描述嵌入向量的平均值）
user_vectors = {}
for user_id, group in df.groupby("user_id"):
    user_game_vecs = []
    for idx, row in group.iterrows():
        g_title = row['game_title']
        g_vec = game_embeddings[g_title]
        user_game_vecs.append(g_vec)
    user_vectors[user_id] = np.mean(np.array(user_game_vecs), axis=0)

# 获取"灭神纪·猢狲"的嵌入向量
target_vector = game_embeddings[target_game]
# 计算每个用户评价的嵌入向量与目标游戏的嵌入向量的余弦相似度
results = []
for user_id, u_vec in user_vectors.items():
    u_vec_reshaped = u_vec.reshape(1, -1)
    t_vec = target_vector.reshape(1, -1)
    similarity = cosine_similarity(u_vec_reshaped, t_vec)[0,0]
    results.append((user_id, similarity))

# 排序并找出最可能喜欢"灭神纪·猢狲"的用户
result_df = pd.DataFrame(results, columns=["user_id", f"similarity_to_{target_game}"])
result_df = result_df.sort_values(by=f"similarity_to_{target_game}", ascending=False)
print(f"\n最可能喜欢{target_game}的前5位用户：")
print(result_df.head())